package ru.jexp.rcp.supply.dnd;

import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;

import ru.jexp.rcp.supply.swtext.JExpControlLookup;

public class JExpDropTarget {

	private DropTarget dragSource;
	private JExpControlLookup lookup;

	public JExpDropTarget(JExpControlLookup lookup) {
		this.lookup = lookup;
		dragSource = new DropTarget(lookup.getControl(), DND.DROP_COPY);
		dragSource.setTransfer(new Transfer[] { TextTransfer.getInstance() });
		dragSource.addDropListener(new DropTargetAdapter() {

			@Override
			public void dragEnter(DropTargetEvent event) {
				if (!canDropObject(event.data)) {
					event.detail = DND.DROP_NONE;
				} else {
					event.detail = DND.DROP_COPY;
				}
			}

			@Override
			public void drop(DropTargetEvent event) {
				dropObject(event.data);
			}
		});
	}

	private void dropObject(Object dropData) {
		lookup.setSelectedElement(dropData);
	}

	private boolean canDropObject(Object dropData) {
		return isAccept(dropData);
	}

	private boolean isAccept(Object dropData) {
		return dropData != null
				&& lookup.getElementType() != null
				&& lookup.getElementType()
						.isAssignableFrom(dropData.getClass());
	}
}
